package com.site.user.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.site.data.QueryResult;
import com.site.user.pojo.TbGroup;
import com.site.user.pojo.TbUser;
import com.site.user.service.ITbPrivilegeService;
import com.site.user.service.ITbUserService;

@Controller
@RequestMapping("/user")
public class TbUserController extends BaseController {
	@Resource
	private ITbUserService tbUserService;
	
	@Resource
	private ITbPrivilegeService tbPrivilegeService;
	

	@RequestMapping(value = "/ser_getUserPrivilege", method = RequestMethod.GET)
	public void getUserPrivilege(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		String msg = "";
		TbUser user = GetLoginSession(request, response);
		if (user != null) {
			msg = tbUserService.getUserPrivilege(user, "");
		}
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		out.println(msg);
	}

	/**
	 * @param request
	 * @param response
	 * @param out
	 * @param entity 保存角色
	 */
	@RequestMapping(value = "/ser_userRoleSave", method = RequestMethod.POST)
	public void userRoleSave(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String msg = "";
		String idUser = ServletRequestUtils.getStringParameter(request, "idUser", "");
		String idRole = ServletRequestUtils.getStringParameter(request, "idRole", "");
		msg = tbUserService.userRoleSave(idUser, idRole);
		out.println(msg);
	}

	/**
	 * @param request
	 * @param response
	 * @param out
	 * @param entity 保存组
	 */
	@RequestMapping(value = "/ser_userGroupSave", method = RequestMethod.POST)
	public void userGroupSave(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String msg = "";
		String idUser = ServletRequestUtils.getStringParameter(request, "idUser", "");
		String idGroup = ServletRequestUtils.getStringParameter(request, "idGroup", "");
		msg = tbUserService.userGroupSave(idUser, idGroup);
		out.println(msg);
	}

	/**
	 * 查询数据列表
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbUser entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String idUser = UUID.randomUUID().toString().replace("-", "");
		entity.setIdUser(idUser);
		String sign = "1";
		entity.setSign(sign);
		tbUserService.execSave(entity);

		String msg = "保存成功.";
		out.println(msg);
	}

	/**
	 * 查询数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_search", method = RequestMethod.POST)
	public void search(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String whereJPQL = "1=1";

		Map mpparam = new HashMap();

		String userName = ServletRequestUtils.getStringParameter(request, "userName", "");
		if (StringUtils.isNotEmpty(userName)) {
			whereJPQL += " and userName like :userName";
			mpparam.put("userName", "%" + userName + "%");
		}

		String nickName = ServletRequestUtils.getStringParameter(request, "nickName", "");
		if (StringUtils.isNotEmpty(nickName)) {
			whereJPQL += " and nickName like :nickName";
			mpparam.put("nickName", "%" + nickName + "%");
		}

		String sex = ServletRequestUtils.getStringParameter(request, "sex", "");
		if (StringUtils.isNotEmpty(sex)) {
			whereJPQL += " and sex =:sex";
			mpparam.put("sex", sex);
		}

		String phone = ServletRequestUtils.getStringParameter(request, "phone", "");
		if (StringUtils.isNotEmpty(phone)) {
			whereJPQL += " and phone =:phone";
			mpparam.put("phone", phone);
		}
		String email = ServletRequestUtils.getStringParameter(request, "email", "");
		if (StringUtils.isNotEmpty(email)) {
			whereJPQL += " and email =:email";
			mpparam.put("email", email);
		}
		String citycode = ServletRequestUtils.getStringParameter(request, "citycode", "");
		if (StringUtils.isNotEmpty(citycode)) {
			whereJPQL += " and citycode =:citycode";
			mpparam.put("citycode", citycode);
		}

		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("idUser", "DESC");

		int pagesize = ServletRequestUtils.getIntParameter(request, "pagesize", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		int maxResult = pagesize * page;
		int startIndex = pagesize * (page - 1);

		QueryResult result = tbUserService.queryData(startIndex, maxResult, whereJPQL, mpparam, orderby);

		out.println(result.getResult("json"));

	}

	/**
	 * 载入全部数据 包括权限
	 * @param request
	 * @param response
	 * @param out
	 */

	@RequestMapping(value = "/ser_load", method = RequestMethod.GET)
	public void load(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String id = ServletRequestUtils.getStringParameter(request, "id", "");
		TbUser obj = null;

		if (StringUtils.isNotEmpty(id)) {

			obj = tbUserService.execFindById(id);
			if (obj != null) {
				JSONObject jobj = new JSONObject(obj);
				out.println(jobj.toString());
			}
		} else {
			out.println("");
		}

	}

	@RequestMapping(value = "/ser_delUserRole", method = RequestMethod.POST)
	public void delUserRole(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String idUser = ServletRequestUtils.getStringParameter(request, "idUser", "");
		String idRole = ServletRequestUtils.getStringParameter(request, "idRole", "");

		String msg = "";

		if ((StringUtils.isNotEmpty(idUser)) && (StringUtils.isNotEmpty(idRole))) {

			msg = tbUserService.delUserRole(idUser, idRole);

		}
		out.println(msg);

	}

	@RequestMapping(value = "/ser_delUserGroup", method = RequestMethod.POST)
	public void delUserGroup(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String idUser = ServletRequestUtils.getStringParameter(request, "idUser", "");
		String idGroup = ServletRequestUtils.getStringParameter(request, "idGroup", "");

		String msg = "";

		if ((StringUtils.isNotEmpty(idUser)) && (StringUtils.isNotEmpty(idGroup))) {

			msg = tbUserService.delUserGroup(idUser, idGroup);

		}
		out.println(msg);

	}

	/**
	 * 载入数据
	 * @param request
	 * @param response
	 * @param out
	 */

	@RequestMapping(value = "/ser_loadDetails", method = RequestMethod.GET)
	public void loadDetails(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String id = ServletRequestUtils.getStringParameter(request, "id", "");
		String idResource = ServletRequestUtils.getStringParameter(request, "idResource", "");
		TbUser obj = null;

		if (StringUtils.isNotEmpty(id)) {

			obj = tbUserService.execFindById(id);
			if (obj != null) {
				JSONObject jobj = new JSONObject(obj);
				String msg = tbUserService.getUserPrivilege(obj, idResource);
				try {
					jobj.put("Privilege", msg);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				out.println(jobj.toString());
			}
		} else {
			out.println("");
		}

	}

	/**
	 * 删除数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String msg = "";
		try {
			String ids = ServletRequestUtils.getStringParameter(request, "ids", "");
			if (StringUtils.isNotEmpty(ids)) {
				String wheresql = " o.idUser in ('" + ids + "')";
				tbUserService.queryDeleteBatch(wheresql);
				msg = "删除成功!";
			}
		} catch (Exception e) {
			msg = "删除数据出现异常!" + e.getMessage();
		}

		out.println(msg);
	}

	/**
	 * 修改数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_update", method = RequestMethod.POST)
	public void update(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbUser entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String msg = "";
		try {
			tbUserService.execUpdate(entity);
			msg = "记录更新成功！";
		} catch (Exception ex) {
			msg = "系统异常，请稍后再试！" + ex.getMessage();
		}
		out.println(msg);

	}
	
	/**
	 * 修改数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_getResOptnById", method = RequestMethod.POST)
	public void getResOptnById(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbUser entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String idUser = ServletRequestUtils.getStringParameter(request, "idUser", "");
		String idResource = ServletRequestUtils.getStringParameter(request, "idResource", "");
		
		TbUser user=tbUserService.execFindById(idUser);
		Object[] idrole= null;
		if("99".equals(user.getSign())){
			idrole=new Object[]{"99"};
		}else{		
			idrole= tbUserService.getUserRolesId(user);
		}
		
		List optlist=tbPrivilegeService.getOptnById(idrole, idResource);
		JSONArray jaArray=new JSONArray(optlist);	
		out.print(jaArray.toString());

	}
	
	/**
	 * 查询数据列表
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_login", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response, PrintWriter out, HttpSession session) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String username = ServletRequestUtils.getStringParameter(request, "username", "");
		String pwd = ServletRequestUtils.getStringParameter(request, "pwd", "");
		String tipmessage = "";

		String jpql = "select c from TbUser c where c.userName='" + username + "'";
		TbUser entity = (TbUser) tbUserService.queryForObject(jpql, TbUser.class);
		if (entity == null) {
			tipmessage = "您输入的用户名不存在，请重新输入。";

		} else if (pwd.equals(entity.getUserPwd())) {
			tipmessage = "登录成功!";
			request.getSession().setAttribute("LOGIN_USER", entity);

		} else {
			tipmessage = "您输入的密码有误，请重新输入。";
		}

		out.println(tipmessage);
	}

}
